<template>
	<view>
		<view class="container">
			<uni-section title="基本信息" type="line">
				<view class="example">
					<!-- 基础用法，不包含校验规则 -->
					<uni-forms ref="form" :modelValue="baseFormData" labelWidth="100px">
						<uni-forms-item label="事项标题" name="sxbt" required>
							<uni-easyinput v-model="baseFormData.sxbt" placeholder="请输入事项标题" />
						</uni-forms-item>
						<uni-forms-item label="事项性质" name="sxxz" required>
							<uni-data-select v-model="baseFormData.sxxz" :localdata="sxxzDict"
								@change="changeSxxzDict"></uni-data-select>
						</uni-forms-item>
            <uni-forms-item label="事项类型" name="sxlx" required>
              <uni-data-select
                  v-model="baseFormData.sxlx"
                  :localdata="sxlxDict"
                  @change="changeSxlxDict"
              ></uni-data-select>
            </uni-forms-item>
						<uni-forms-item label="紧急程度" name="jjcd" required>
							<uni-data-checkbox v-model="baseFormData.jjcd" :localdata="jjcdDict"
								@change="changeJjcdDict" />
						</uni-forms-item>
						<uni-forms-item label="间隔时间" name="jgsj" required v-if="baseFormData.jjcd === '2'">
							<uni-data-select v-model="baseFormData.jgsj" :localdata="jgsjDict"
								@change="changeJgsjDict"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="是否反馈" name="sffk" required>
							<uni-data-checkbox v-model="baseFormData.sffk" :localdata="sffkDict"
								@change="changeSffkDict" />
						</uni-forms-item>
						<uni-forms-item label="截止日期" name="jzrq" required v-if="baseFormData.sffk === '1'">
							<uni-datetime-picker type="date" v-model="baseFormData.jzrq" />
						</uni-forms-item>
            <uni-forms-item label="下达内容" name="xdnr">
              <uni-easyinput autoHeight  type="textarea"  v-model="baseFormData.xdnr"/>
            </uni-forms-item>
					</uni-forms>
					<el-row>
						<el-col :span="6">
							<label>相关文件：</label>
						</el-col>
						<el-col :span="18">
							<el-upload class="upload-demo" :action="uploadParam.uploadUrl"
								:headers="uploadParam.headers" :before-upload="rwBeforeUpload" :on-change="handleChange"
								:on-error="handleUploadError" :on-success="handleUploadSuccess" :auto-upload="true"
								:on-remove="removeFile" ref="upload" multiple :file-list="uploadParam.fileList">
								<el-button slot="trigger" ref="uploadInput" size="small">选择文件</el-button>
							</el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</view>
				<view class="action-btn fixed-bottom">
					<button @click="submitFrom" class="bg-blue lg round">提交</button>
				</view>
			</uni-section>
			<uni-section title="下达目标" type="line">
				<view style="margin-left: 50rpx;height: 400rpx;">
					<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
					<div style="margin: 15px 0;"></div>
					<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
					  <el-checkbox v-for="city in cities" :label="city.deptId" :key="city.deptId">{{city.deptName}}</el-checkbox>
					</el-checkbox-group>
				</view>
			</uni-section>
		</view>
	</view>
</template>

<script>
	import {
		getDicts
	} from "@/api/system/dict/data";
	import {
		addAppZjxdwj,
		getAppCityLevel
	} from "@/api/system/yjgl";
	import config from '@/config';
	import {
		getToken,
		getUsername
	} from '@/utils/auth'

	export default {
		data() {
			return {
				isIndeterminate: true,
				checkAll: false,
				checkedCities: [],
				cityOptions: [],
			    cities:[],
				workid: "",

				submitLoading: false,
				// 基础表单数据
				baseFormData: {
					sxbt: "",
					sxxz: "",
					jjcd: "",
					jgsj: "",
					sffk: "",
					jzrq: "",
					rwlx: "",
          xdnr:"",
				},
				sxxzDict: [],
        sxlxDict: [],
        sffkDict: [],
				jjcdDict: [],
				jgsjDict: [{
						value: "0.5",
						text: "半小时"
					},
					{
						value: "1",
						text: "1小时"
					},
					{
						value: "2",
						text: "2小时"
					},
					{
						value: "3",
						text: "3小时"
					},
					{
						value: "5",
						text: "5小时"
					},
					{
						value: "8",
						text: "8小时"
					},
					{
						value: "12",
						text: "12小时"
					},
					{
						value: "24",
						text: "24小时"
					},
					{
						value: "48",
						text: "48小时"
					}
				],
				rules: {
					sxbt: {
						rules: [{
							required: true,
							errorMessage: '事项标题不能为空'
						}]
					},
					sxxz: {
						rules: [{
							required: true,
							errorMessage: '请选择事项性质'
						}]
					},
					jjcd: {
						rules: [{
							required: true,
							errorMessage: '请选择紧急程度'
						}]
					},
					sffk: {
						rules: [{
							required: true,
							errorMessage: '请选择是否反馈'
						}]
					},
					jzrq: []
				},

				uploadParam: {
					// 上传的图片服务器地址
					uploadUrl: config.baseUrl + "/common/upload",
					headers: {
						Authorization: "Bearer " + getToken()
					},
					fileType: [
						["doc", "xls", "ppt", "txt", "pdf"],
					],
					fileList: [],
				},
			}
		},
		created() {
			// 字典翻译
			getDicts("sxxz").then(response => {
				for (let item of response.data) {
					this.sxxzDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
      getDicts("sxlx").then(response => {
        for (let item of response.data) {
          this.sxlxDict.push({"text": item.dictLabel, "value": item.dictValue})
        }
      });
			getDicts("sffk").then(response => {
				for (let item of response.data) {
					this.sffkDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			getDicts("jjcd").then(response => {
				for (let item of response.data) {
					this.jjcdDict.push({
						"text": item.dictLabel,
						"value": item.dictValue
					})
				}
			});
			this.getAppCityLevel();
			this.workid = new Date().getTime() + Math.random().toString(36).substr(2);
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			getAppCityLevel(){
			  getAppCityLevel({username:  getUsername()}).then(res=>{
				if (res.code==200){
				  this.cityOptions = res.data;
				  this.cities = this.cityOptions;
				}
			  })
			},
			handleCheckAllChange(val) {
			  this.checkedCities = val ? this.cityOptions.map(m=>m.deptId) : [];
			  this.isIndeterminate = false;
			},
			handleCheckedCitiesChange(value) {
			  let checkedCount = value.length;
			  this.checkAll = checkedCount === this.cities.length;
			  this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
			},
			submitFrom() {
				this.$refs.form.validate().then(res => {
          if (this.checkedCities.length==0){
            this.$modal.msgError("请选择转达部门");
            return false;
          }
					if (this.baseFormData.jjcd === '2' && this.baseFormData.jgsj == "") {
						this.$modal.msgError("请选择间隔时间");
						return false;
					}
					if (this.baseFormData.jjcd === '1') {
						this.baseFormData.jgsj = ""
					}

					if (this.baseFormData.sffk === '1' && this.baseFormData.jzrq == "") {
						this.$modal.msgError("请选择截止日期");
						return false;
					}
					if (this.baseFormData.sffk === '2') {
						this.baseFormData.jzrq = ""
					}
					this.baseFormData.rwlx = "1";
					console.log(this.baseFormData)
					const data = {
						"username": getUsername(),
						"zjxdRwb": this.baseFormData,
						"fjbs": this.uploadParam.fileList,
						"workid": this.workid,
						"deptIds": this.checkedCities
					  }
					console.log(data)
					addAppZjxdwj(data).then(res => {
					  this.submitLoading = false;
					  this.$modal.msgSuccess("添加成功");
					  uni.navigateBack();
					}).catch(err => {
						console.log('err', err);
						this.$modal.msgError("添加失败");
						this.submitLoading = false;
					});
				}).catch(err => {
					console.log('err', err);
				})
			},
			changeSxxzDict(e) {
				this.baseFormData.sxxz = e
			},
      changeSxlxDict(e){
        this.baseFormData.sxlx = e
      },
			changeJjcdDict(e) {
				this.baseFormData.jjcd = e.detail.value
			},
			changeJgsjDict(e) {
				this.baseFormData.jgsj = e
			},
			changeSffkDict(e) {
				this.baseFormData.sffk = e.detail.value
			},
			submitUpload() {
				this.$refs.upload.submit();
			},
			// 上传失败
			handleUploadError(err) {
				console.log("上传失败...")
				this.$modal.msgError("上传文件失败，请重试");
				this.$modal.closeLoading();
			},
			rwBeforeUpload(file) {
				console.log("上传前...");
			},
			handleChange(file, fileList) {
				this.uploadParam.fileList = fileList;
			},
			// 上传成功回调
			handleUploadSuccess(res, file) {
				console.log("上传成功...");
			},
			// 移除附件操作
			removeFile(file, fileList) {
				this.uploadParam.fileList = fileList;
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f6f7;
	}

	.container {
		background-color: white;
		margin: 20rpx;
		border-radius: 20rpx;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.fixed-bottom {
		position: fixed;
		bottom: var(--window-bottom);
		bottom: 0;
		width: 95%;
		margin-bottom: 20rpx;
	}

	.two_button {
		display: flex;
	}

	.article {
		background-color: white;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.tabClass {
		font-size: 80rpx;
		margin-left: 40rpx;
		margin-right: 400rpx;
	}
</style>
